package br.com.upis.sispat.service.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import br.com.upis.sispat.dao.Dao;
import br.com.upis.sispat.entity.Setor;
import br.com.upis.sispat.exception.SeamCoreException;
import br.com.upis.sispat.service.SetorService;

@Service("setorService")
public class SetorServiceImpl implements SetorService {

	private Dao<Setor> setorDao;

	private static final long serialVersionUID = -3306452448892268624L;

	@SuppressWarnings("unchecked")
	public List<Setor> search(Setor setor) throws SeamCoreException {

		StringBuilder hql = new StringBuilder();
		hql.append(" select u from Setor u ");
		hql.append(" where 1=1 ");

		List<String> listaParam = new ArrayList<String>();

		if (setor.getNomeSetor() != null
				&& setor.getNomeSetor().length() > 0) {
			hql.append(" and u.nomeSetor like ? ");
			listaParam.add(setor.getNomeSetor());
		}

		if (setor.getSigla() != null && setor.getSigla().length() > 0) {
			hql.append(" and u.sigla = ? ");
			listaParam.add(setor.getSigla());
		}

		int i = 0;

		Session session = setorDao.getSession();

		Transaction tx = session.getTransaction();

		tx.begin();

		Query query = session.createQuery(hql.toString());

		if (setor.getNomeSetor() != null
				&& setor.getNomeSetor().length() > 0) {

			query.setString(i++, "%" + setor.getNomeSetor() + "%");
		}

		if (setor.getSigla() != null && setor.getSigla().length() > 0) {
			query.setString(i++, setor.getSigla());
		}

		List<Setor> lista = query.list();

		tx.commit();

		return lista;
	}

	@Override
	@Transactional
	public void save(Setor setor) throws SeamCoreException {
		setor.setCodigo(1L);
		try {
			setorDao.create(setor);
		} catch (SQLException e) {
			throw new SeamCoreException(e);
		}

	}

	@Override
	@Transactional
	public void delete(Setor setor) throws SeamCoreException {
		try {
			setorDao.delete(setor);
		} catch (SQLException e) {
			throw new SeamCoreException(e);
		}

	}

	@Override
	@Transactional
	public void update(Setor setor) throws SeamCoreException {
		try {
			setorDao.update(setor);
		} catch (SQLException e) {
			throw new SeamCoreException(e);
		}

	}

	public Setor getById(Long id) {

		return setorDao.getObjectFromId(Setor.class, id);
	}

	@Autowired
	public void setSetorDao(Dao<Setor> setorDao) {
		this.setorDao = setorDao;
	}

}
